#!/usr/bin/env python
# coding=utf-8

import sys
import feedparser
import urllib
import urllib2
import time
import datetime
from google.appengine.api import memcache
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db
from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex.babel import Section
from v2ex.babel import Node
from v2ex.babel import Topic
from v2ex.babel import Reply
from xml.sax.saxutils import unescape     
        
username = 'xiaox.china@gmail.com'
password = 'luoyan520'

# Authenticate to obtain SID
auth_url = 'https://www.google.com/accounts/ClientLogin'
auth_req_data = urllib.urlencode({'Email': username,
                                  'Passwd': password,
                                  'service': 'reader'})
auth_req = urllib2.Request(auth_url, data=auth_req_data)
auth_resp = urllib2.urlopen(auth_req)
auth_resp_content = auth_resp.read()
auth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\n') if x)
auth_token = auth_resp_dict["Auth"]

# Create a cookie in the header using the SID 
header = {}
header['Authorization'] = 'GoogleLogin auth=%s' % auth_token

reader_base_url = 'http://www.google.com/reader/atom/user/-/state/com.google/reading-list?%s'
reader_req_data = urllib.urlencode({'r': 'o',
                                    'ot': int(time.time()-360)})
reader_url = reader_base_url % (reader_req_data)
reader_req = urllib2.Request(reader_url, None, header)
reader_resp = urllib2.urlopen(reader_req)
reader_resp_content = reader_resp.read()

d = feedparser.parse(reader_resp_content)
for entry in d.entries:
    #print entry.title
    q = db.GqlQuery("SELECT * FROM Node WHERE name = :1", 'feed')
    node = False
    if (q.count() == 1):
        node = q[0]

    topic = Topic(parent=node)
    q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1', 'topic.max')
    if (q.count() == 1):
        counter = q[0]
        counter.value = counter.value + 1
    else:
        counter = Counter()
        counter.name = 'topic.max'
        counter.value = 1
    q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1', 'topic.total')
    if (q2.count() == 1):
        counter2 = q2[0]
        counter2.value = counter2.value + 1
    else:
        counter2 = Counter()
        counter2.name = 'topic.total'
        counter2.value = 1
    topic.num = counter.value
    topic.title = unescape(entry.title)
    topic.content = 'Original Link: ' + '<a href="'+entry.link+'" target="_blank">'+entry.link+'</a><br/>' + unescape(entry.summary) 
    topic.content_rendered = topic.content
    topic.node = node
    topic.node_num = node.num
    topic.node_name = node.name
    topic.node_title = node.title
    topic.created_by = entry.author_detail.name
#topic.member = member
#topic.member_num = member.num
    topic.last_touched = datetime.datetime.now()
    topic.source = 'FeedParser'
    node.topics = node.topics + 1
    node.put()
    topic.put()
    counter.put()
    counter2.put()
    memcache.delete('feed_index')
    memcache.delete('Node_' + str(topic.node_num))
    memcache.delete('Node::' + str(node.name))
    memcache.delete('home_rendered')
    memcache.delete('home_rendered_mobile')
    taskqueue.add(url='/index/topic/' + str(topic.num))
    
